﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.IO;

namespace AudioCore.Common
{
    public class StringUtils
    {
        public const string LF_CHAR = "\\n";
        public const string CRLF = "\r\n";
        public const string SPACE = " ";

        public static string Trim(string str)
        {
            const string space2 = "  ";
            const string space1 = " ";
            int index = 0;
            str = str.Trim();
            do
            {
                index = str.IndexOf(space2);
                if (index > -1)
                    str = str.Replace(space2, space1);
            }
            while (index > -1);
            return str;
        }

        private static NameValueCollection UnicodeChars = null;

        private static void InitUnicodeChars()
        {
            if (UnicodeChars == null)
            {
                UnicodeChars = new NameValueCollection();
                try
                {
                    //StreamReader readerUnicode = new StreamReader(Properties.Resources.unicodechars);
                    //StreamReader readerAscii = new StreamReader(Properties.Resources.asciichars);
                    //string uch = string.Empty;
                    //string ach = string.Empty;
                    //while ((uch = readerUnicode.ReadLine()) != null)
                    //{
                    //    ach = readerAscii.ReadLine();
                    //    UnicodeChars.Add(uch, ach);
                    //}

                    string[] uchs = Properties.Resources.UnicodeChars.Split(new char[] { ' ' });
                    string[] achs = Properties.Resources.AsciiChars.Split(new char[] { ' ' });
                    for (int i = 0; i < Math.Min(uchs.Length, achs.Length); i++)
                    {
                        UnicodeChars.Add(uchs[i], achs[i]);
                    }
                }
                catch (Exception ex)
                {
                    // No action
                    Console.WriteLine(ex.ToString());
                }
            }
        }

        public static string DecomposeUnicode(string s)
        {
            InitUnicodeChars();

            if (UnicodeChars == null || UnicodeChars.Count == 0)
                return s;

            for (int i = 0; i < UnicodeChars.Count; i++)
            {
                string key = UnicodeChars.GetKey(i);
                string[] values = UnicodeChars.GetValues(key);
                if (key == null || values == null || values.Length < 1 || values[0] == null)
                    continue;
                s = s.Replace(key, values[0]);
            }
            return s;
        }
    }
}
